package com.xunmall.executors.framework.policy;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.RejectedExecutionHandler;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.atomic.AtomicLong;

/**
 * @author wangyj03@zenmen.com
 * @description
 * @date 2020/9/28 16:52
 */
public class CountableRejectedExecutionHandler implements RejectedExecutionHandler, Countable {

    private Logger logger = LoggerFactory.getLogger(getClass());

    private RejectedExecutionHandler executionHandler;

    /***
     * @Description: [值读取一次就被清零，重新计数（只用于监控时上报）]
     * @Title:
     * @Author: WangYanjing
     * @Date: 2020/9/28
     * @Param: null
     * @Return: null
     * @Throws:
     */
    private AtomicLong counter = new AtomicLong(0);

    public CountableRejectedExecutionHandler(RejectedExecutionHandler handler) {
        this.executionHandler = handler;
    }

    @Override
    public long count() {
        return counter.getAndSet(0);
    }

    @Override
    public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {
        try {
            counter.incrementAndGet();
            executionHandler.rejectedExecution(r, executor);
        } catch (Exception ex) {
            logger.error("rejectedExecution occurred", ex);
        }
    }
}
